package com.miyu.system.service.sys.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.miyu.common.utils.commonUtils.RedisCache;
import com.miyu.common.utils.taskJob.AopTaskCache;
import com.miyu.common.utils.taskJob.RedisTaskCahe;
import com.miyu.system.dao.sys.CosSysUserSystemDao;
import com.miyu.system.service.sys.UserService;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 用户服务impl
 *
 * @author longmy
 * @date 2022/03/22
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private CosSysUserSystemDao cssdDao;
    /**
     * 用户登录
     * @param param
     * @return
     */
    @Override
    public JSONObject userLogin(JSONObject param) {
        JSONObject rs = new JSONObject();
        //获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        String user = param.getString("userAccount");
        String check = param.getString("checkCode");
        //验证码校验
        String ip =getIpAddr(request);
        String checkImpCode="";
        ip=ip.replace(".","");
       /* if(RedisCache.hasKey(ip+"_CheckImgCode")){
            checkImpCode = RedisCache.get(ip+"_CheckImgCode").toString();
        }
        if (checkImpCode.length()>0){
            if(!check.equals(checkImpCode)){
                rs.put("code","-1");
                rs.put("msg","验证码错误,请重新填写");
                return rs;
            }
        }else {
            rs.put("code","-1");
            rs.put("msg","验证码错误,请重新填写");
            return rs;
        }*/

        //登录账号
       JSONObject userInfo = queryUserInfo(user);
        //判断什么账号登录 支持 账号 ,邮箱 ,手机号
        // 1 账户 2 邮箱 3 手机
        String nowDate = DateUtil.now();
        if(userInfo.size()>0){
            String  type="0";
            type = checkLogin(userInfo,param);
            switch (type){
                case "1":
                    StpUtil.login(user,"1");
                    break;
                case "2":
                    StpUtil.login(user,"2");
                    break;
                case "3":
                    StpUtil.login(user,"3");
                    break;
                case "-1":
                    //密码错误
                    break;
                default:
                    break;
            }
            if(type!="-1"){
                ExecutorService exec = Executors.newCachedThreadPool();
                System.out.println(StpUtil.getTokenInfo());
                //返回前端数据
                rs.put("code","1");
                rs.put("userId",userInfo.getString("cosId"));
                rs.put("cosName",userInfo.getString("cosName"));
                rs.put("satoken",StpUtil.getTokenValue());
                rs.put("loginDate",nowDate);
                rs.put("accountType",type);
                //用户信息存储
                JSONObject userCache = new JSONObject();
                userCache.put(user,userInfo);
                String key = "cos_sys_user";
                exec.submit(new RedisTaskCahe(key, userCache));

                StpUtil.getTokenSession().set("key",rs);
                //写入登录日志
                JSONObject log = new JSONObject();
                log.put("cosAccount",user);
                log.put("accountType",type);
                log.put("cosName","李四");
                log.put("logDate", nowDate);
                log.put("logIp",getIpAddr(request));
                log.put("saToken",StpUtil.getTokenValue());
                //提交登录日志
                exec.submit(new RedisTaskCahe(1,1,"cosLoginLog",log));
                return rs;
            }
        }else{
            rs.put("code","-1");
            rs.put("msg","登录账户不存在");
        }
        return rs;
    }

    /**
     * 用户退出
     * 清理token 缓存
     * @param param
     * @return
     */
    @Override
    public JSONObject userloginOut(JSONObject param) {
        JSONObject jo = new JSONObject();
        if(StpUtil.isLogin()){
            StpUtil.logoutByTokenValue(param.getString("token"));
            jo.put("msg","已成功");
        }else {
            jo.put("msg","当前未登录,无需退出");
        }
        return jo;
    }

    //登录校验
    private String checkLogin(JSONObject userInfo, JSONObject param) {
        String type = "0";
        String user = param.getString("userAccount");
        String password = param.getString("password");
        //账号
        if (user.equals(userInfo.getString("cosAccount"))) {
            //密码校验
            type = "1";
        } else
            // 邮箱
        if (user.equals(userInfo.getString("cosEmail"))) {
            type = "2";
        } else
        //手机号
        if (user.equals(userInfo.getString("cosPhone"))) {
            type = "3";

        }

        return type;
    }

    /**
     * 获取登录信息
     * @param user
     * @return
     */
    public JSONObject queryUserInfo(String user){
        JSONObject rs = new JSONObject();
        StringBuffer sql = new StringBuffer();
        sql.append(" select * from ");
        sql.append(" cos_sys_user ");
        sql.append(" where cos_account ='");
        sql.append(user).append("' or cos_email = '").append(user).append("' or cos_phone = '").append(user).append("'");
        rs = cssdDao.queryJSONObjectBySql(sql.toString());
        return rs;
    }
    public static String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if(ip!=null|| ip.length() >0){
            String[]  ipStr =ip.split(",");
            ip=ipStr[0];
        }
        if(ip ==null || ip.length() ==0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip ==null || ip.length() ==0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip ==null || ip.length() ==0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
